<script setup lang="ts">
import { reactive, ref, onBeforeMount,onMounted} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { user as useUser } from '@/store'
import type { loginFormInfoType } from './type'
import { ElMessage as message } from 'element-plus'
import md5 from 'blueimp-md5'
import { PRIVATE_KEY } from '@/common/config'
import { verifyPic as _verifyPic } from '@/assets/imgs/verifyPic'

const router = useRouter()
const route = useRoute()

const userStore = useUser()

const formState: loginFormInfoType = reactive({
	userName: '',
	password: '',
	verifyCode: 'tky8',
	remember: true,
})

const isLoading = ref(false)

const formRef = ref<FormInstance>()

const verifyPic = ref<string>('')
const verifyCodeKey = ref<string>('')
const verifyCode = ref<string>('')
let inputList:NodeListOf<HTMLElement>

const rules = reactive<FormRules>({
	userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
	verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})

onBeforeMount(() => {
	console.log('超级管理员账号：admin，密码：admin')
	bindToggleVerifyPic()
	verifyPic.value = _verifyPic
	const { remember, userName, password } = userStore.loginInfo
	if (remember && userName && password) {
		formState.userName = userName
		formState.password = password
		formState.remember = remember
	}
	if(typeof remember=='boolean')
   formState.remember=remember
})

onMounted(()=>{
	inputList=document.querySelectorAll('.account-form .el-input__inner')
})

function bindToggleVerifyPic() {
	console.log('发送请求切换验证码')
}

function handleInputsKeyDown(e: KeyboardEvent){
  if(e.key=='ArrowUp' || e.key=='ArrowDown') e.preventDefault()
}

function handleInputsKeyUp(index:number,e: KeyboardEvent) {
	if (e.key == 'Enter') submitForm(formRef.value)
	const toggleFocus=(direction:'down' | 'up')=>{
		let i:number
		if(direction=='up'){
			i=index-1
		  if(i<0) i=inputList.length-1
		}
		else{
			i=index+1
		  if(i>inputList.length-1) i=0
		}
		inputList[i].focus()	
  }
	if(e.key=='ArrowUp'){
		toggleFocus('up')
	}
	if(e.key=='ArrowDown'){
		toggleFocus('down')
	}
}

function resetForm(formEl: FormInstance | undefined) {
	if (!formEl) return
	formEl.resetFields()
}

function submitForm(formEl: FormInstance | undefined) {
	if (!formEl) return
	formEl.validate(async (valid) => {
		if (valid) {
			if (isLoading.value) return
			isLoading.value = true
			const res = await userStore.loginByAccount({ userName: formState.userName, password: md5(formState.password, PRIVATE_KEY) })
			isLoading.value = false

			if (res && res.code == 200) {
				const { id } = userStore.loginInfo
				if (route.query.redirect && res.id === id)
				// 防止重定向到没有权限的页面
				router.push(decodeURIComponent(route.query.redirect as string))
				else router.push('/')
				if (formState.remember) {
					userStore.$patch((s) => {
						const {
							loginInfo: { phone },
						} = s
						const obj: loginFormInfoType = { phone, id: res.id, activeTab: 'account', ...formState }
						delete obj.verifyCode
						s.loginInfo = obj
					})
				} else {
					userStore.$patch((s) => {
						const {
							loginInfo: { phone },
						} = s
						s.loginInfo = { password: '', userName: '', remember: false, phone, id: res.id, activeTab: 'account' }
					})
				}
			}
			if (res && res.code == 201) message.warning('用户名或者密码错误！')
		} else {
			//console.log('error submit!')
			return false
		}
	})
}
</script>

<template>
	<el-form class="account-form" status-icon ref="formRef" :model="formState" :rules="rules">
		<el-form-item prop="userName">
			<el-input v-model="formState.userName" placeholder="用户名" clearable prefix-icon="User" @keyup="handleInputsKeyUp(0,$event)" @keydown="handleInputsKeyDown"></el-input>
		</el-form-item>

		<el-form-item prop="password">
			<el-input v-model="formState.password" placeholder="密码" type="password" show-password clearable prefix-icon="Lock" @keyup="handleInputsKeyUp(1,$event)" @keydown="handleInputsKeyDown"></el-input>
		</el-form-item>

		<el-form-item prop="verifyCode">
			<el-input v-model="formState.verifyCode" placeholder="请输入验证码" prefix-icon="Key" style="width: 60%; margin-right: 10px" @keyup="handleInputsKeyUp(2,$event)" @keydown="handleInputsKeyDown"></el-input>
			<img style="width: 35%; height: 32px" :src="verifyPic" @click="bindToggleVerifyPic" />
		</el-form-item>

		<el-form-item label="" prop="remember">
			<div style="width: 100%">
				<el-checkbox v-model="formState.remember">记住密码</el-checkbox>
				<el-link type="primary" class="login-form-forgot" href="javascript:;" :underline="false">忘记密码</el-link>
			</div>
		</el-form-item>

		<el-form-item>
			<el-button style="width: 100%" type="primary" @click="submitForm(formRef)" :loading="isLoading">登录</el-button>
			<!-- <el-button @click="resetForm(formRef)">Reset</el-button> -->
		</el-form-item>
	</el-form>
</template>

<style scoped lang="scss">
.login-form-forgot {
	float: right;
}
</style>
